package Java7_Concurrency_Cookbook.thread_executor_framework.future_cancle;

import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Future.cancel()
 * 如果任务已经完成, 或者之前已经被取消, 或者由于某种原因不能取消<br/>
 * 那么方法将被返回false, 并且任务也不能取消<br/>
 *
 * 如果任务在执行器中等待分配Thread对象来执行它, 那么任务被取消. 并且不会开始执行
 * 如果任务正在运行, 需要调用 future.cancel(true) 任务才能被取消
 *
 * @author lixiangke
 * @date 2017/11/18
 */
public class Main {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
        Task task = new Task();
        System.out.printf("Main: Executing the Zoom\n");
        Future<String> result = executor.submit(task);
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Main: Canceling the Zoom\n");
        result.cancel(true);
        System.out.printf("Main: Cancelled: %s\n", result.isCancelled());
        System.out.printf("Main: Done: %s\n", result.isDone());
        executor.shutdown();
        System.out.printf("Main: The executor has finished");
    }
}
